import CreateInterface from '@/pages/Admin/components/CreateInterface';
import UpdateInterface from '@/pages/Admin/components/UpdateInterface';
import { removeRule } from '@/services/ant-design-pro/api';
import {
  getInterfaceInfoListPage,
  postInterfaceInfoAdd,
  postInterfaceInfoOffline,
  postInterfaceInfoOnline,
  postInterfaceInfoOpenApiDelete,
  postInterfaceInfoUpdate,
} from '@/services/LarlyAPI_backend/interfaceInfoController';
import { PlusOutlined } from '@ant-design/icons';
import type {
  ActionType,
  ProColumns,
  ProDescriptionsItemProps,
  RequestData,
} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import { Button, Drawer, message } from 'antd';
import type { SortOrder } from 'antd/lib/table/interface';
import React, { useRef, useState } from 'react';

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.RuleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};
const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfoVo>();
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfoVo[]>([]);

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.InterfaceInfoVo) => {
    const hide = message.loading('正在添加');
    try {
      await postInterfaceInfoAdd({
        id: currentRow?.id,
        ...fields,
      });
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败');
      return false;
    }
  };
  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfoVo) => {
    const hide = message.loading('修改中');
    try {
      await postInterfaceInfoUpdate({
        id: currentRow?.id,
        ...fields,
      });
      hide();
      message.success('修改成功');
      handleUpdateModalOpen(false);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('修改失败 w');
      return false;
    }
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.InterfaceInfoVo>[] = [
    {
      title: 'id',
      valueType: 'index',
      hideInForm: true,
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '描述',
      dataIndex: 'descrpition',
      valueType: 'textarea',
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'textarea',
    },
    {
      title: '响应头',
      dataIndex: 'responeHeader',
      valueType: 'textarea',
    },
    {
      title: '接口地址',
      dataIndex: 'url',
      valueType: 'text',
    },
    {
      title: '接口类型',
      dataIndex: 'method',
      valueType: 'text',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'date',
      hideInForm: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '运行中',
          status: 'Processing',
        },
      },
    },
    {
      title: '接口使用次数',
      dataIndex: 'count',
      sorter: true,
      hideInForm: true,
      renderText: (val: string) => `${val}${'次'}`,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <a
          key="configDel"
          onClick={async () => {
            // console.log(record?.id);
            try {
              const res = await postInterfaceInfoOpenApiDelete({
                id: record?.id,
              });
              if (res.data) {
                message.success('删除成功');
              }
            } catch (e) {
              message.error('删除失败');
              actionRef.current?.reload();
            }
          }}
        >
          删除
        </a>,
        record.status === 0 && (
          <a
            key="publish"
            onClick={async () => {
              try {
                await postInterfaceInfoOnline({
                  id: record?.id,
                });
                actionRef.current?.reload();
                message.success('上架成功');
              } catch (e) {
                message.error('上架失败');
              }
            }}
          >
            上架
          </a>
        ),
        record.status === 1 && (
          <a
            key="offline"
            onClick={async () => {
              try {
                await postInterfaceInfoOffline({
                  id: record?.id,
                });
                actionRef.current?.reload();
                message.success('上架成功');
              } catch (e) {
                message.error('上架失败');
              }
            }}
          >
            下架
          </a>
        ),
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.InterfaceInfoQueryRequest>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (
          params: API.InterfaceInfoQueryRequest & {
            pageSize?: number;
            current?: number;
            keyword?: string;
          },
          sort: Record<string, SortOrder>,
        ): Promise<RequestData<API.InterfaceInfoVo | undefined>> => {
          const sortField = Object.keys(sort)[0];
          const sortOrder = sort[sortField] === 'descend' ? 'des' : 'asc';
          const res = await getInterfaceInfoListPage(
            {
              pageNum: params.current,
              pageSize: params.pageSize,
              name: params.name,
              descrpition: params.descrpition,
              url: params.url,
              method: params.method,
              status: params.status,
              sortField: sortField,
              sortOrder: sortOrder,
            },
            {},
          );

          if (res?.data) {
            return {
              data: res.data.list || [],
              success: true,
              total: res.data.total,
            };
          }

          return {
            data: [],
            success: false,
            total: 0,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
      {/*  创建接口窗口  */}
      <CreateInterface
        onCancel={() => handleModalOpen(false)}
        onSubmit={handleAdd}
        open={createModalOpen}
        columns={columns}
      />
      {/*  修改接口窗口  */}
      <UpdateInterface
        values={currentRow}
        onCancel={() => handleUpdateModalOpen(false)}
        onSubmit={handleUpdate}
        open={updateModalOpen}
        columns={columns}
      />
    </PageContainer>
  );
};
export default TableList;
